package com.example.a410.mybt;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.a410.mybt.ExcelUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.a410.mybt.MainActivity.mMainActivity;

public class ChatActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<Msg>();

    private EditText inputText;

    private Button send;
    private Button export;

    private RecyclerView msgRecyclerView;
    private int bufSize=100;
    private MsgAdapter adapter;
    public static final String TAG="WANGDA";
    private final String xlsPath = ExcelUtils.getSDPath(mMainActivity) + "/test.xls";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initMsgs(); // 初始化消息数据
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        export = findViewById(R.id.export);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        msgList.clear();
        PermisionUtils.verifyStoragePermissions(mMainActivity);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕唤醒
        String[] i = {"顺序号", "测量值(mm)","损耗面积(mm2)","损耗百分比(%)","接触线残留高度(mm)"};
        ExcelUtils.initExcel(xlsPath, i, mMainActivity);
        Toast.makeText(mMainActivity, "请使用正确的数据格式发送数据，点击导出EXCEL按钮，可在SD卡根目录获取表格文件", Toast.LENGTH_LONG).show();
        mMainActivity.setHasNewMessage(0);
// https://stackoverflow.com/questions/16872419/android-standard-way-to-make-a-thread-run-every-second
        final ExecutorService es = Executors.newCachedThreadPool();
        ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                es.submit(new Runnable() {
                    @Override
                    public void run() {
                        if (mMainActivity.getHasNewMessage() == 1) {
                            mMainActivity.setHasNewMessage(0);
                            Msg receive = new Msg("" + mMainActivity.getmReadMasssage(), Msg.TYPE_RECEIVED);
                            Log.d(TAG, "SEND");
                            bufSize = msgList.size();
                            msgList.add(receive);
                            mChatHandler.sendEmptyMessage(0);
                        }
                    }
                });
            }
        }, 0, 100, TimeUnit.MICROSECONDS);
      //  LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        LinearLayoutManager linearLayoutManager=new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        msgRecyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if (!"".equals(content)) {
                    if (mMainActivity.getBlueToothIsConnented()) {
                        mMainActivity.sendData(content);
                    } else {
                        Toast.makeText(ChatActivity.this, "未连接设备，信息发送失败，请返回重新连接.", Toast.LENGTH_SHORT).show();
                    }
                    Msg msg = new Msg(content, Msg.TYPE_SENT);
                    msgList.add(msg);
                    mChatHandler.sendEmptyMessage(0);
                    inputText.setText(""); // 清空输入框中的内容
                }
            }
        });
        export.setOnClickListener(new View.OnClickListener(){
            int for_i=0;
            @Override
            public void onClick(View v){
                ArrayList<dataMsg> numList = new ArrayList<>();
                for(int i=0;i<msgList.size();i++)
                {
                    String[] data = new String[5];
                    dataMsg DataMsg1 = new dataMsg(data);
                    String pattern = "\\d+\\.?\\d*";
                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(msgList.get(i).getContent());
                    for_i=0;
                    while (m.find()) {
                        if(for_i >= 5)break;
                        data[for_i++] = m.group();
                        Log.d("WANGDA", "" + data[for_i-1]);
                    }
                    numList.add(DataMsg1);
                }
                ExcelUtils.writeObjListToExcel(numList, xlsPath, mMainActivity);
            }
        });
    }
    // 需要一个一直在运行的函数，用于输出接收到的信息。
    private Handler mChatHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            adapter.notifyItemInserted(msgList.size() - 1); // 当有新消息时，刷新ListView中的显示
            msgRecyclerView.scrollToPosition(msgList.size() - 1); // 将ListView定位到最后一行
            Log.d(TAG, "msgList size " + msgList.size() + ",List Data " + msgList.get(msgList.size() - 1).getContent());
        }
    };
    private void initMsgs() {
        String phoneName = mMainActivity.getPhoneName();
        Msg msg1 = new Msg("Hello, " + phoneName + ".", Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("Hello. Who is that?", Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3 = new Msg("This is Tom. Nice talking to you. ", Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}

